package net.sk.cam;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.HashMap;

import net.bat.util.Cfg;
import net.sk.gti.gtiData;
import net.sk.jni.Plate;
import net.sk.mina.imagine.ImgServlet;
import net.sk.pt.IProvider;
import net.sk.pt.State;
import net.sk.web.Keeper;
import net.sk.web.Provider;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;


public class CamIoHandler extends IoHandlerAdapter {
	static final boolean bjni = false;
	//本地调用对象
	Plate plt = null;
	//心跳帧回送
	static public final int ack= 0x55AA55AA;
	
    public static final int CONNECT_TIMEOUT = 3000;
    public static final int CONNECT_SPAN = 10000;
    public static final String IMG_FMT = "png";

    public static String PR_CAMERA="PR_CAMERA_";
    public static String CN_CAMERA="CN_CAMERA";
    
	static String[] RS = new String[]{
		"[[\"京A778899\",\"蓝\",\"类型1\",10,10,30,30,0.99,10]]",
		"[[\"京A111111\",\"黑\",\"类型2\",10,10,30,30,0.99,10],[\"川A9876543\",\"蓝\",\"类型5\",80,80,120,100,0.95,33]]",
		"[[\"川B141414\",\"黄\",\"类型3\",80,80,120,100,0.95,33]]"
	};
	int pos_rs=0;

	
	
	public CamIoHandler(){
	}
	public IProvider getPR(long oid){
		String prn = PR_CAMERA+oid;
		IProvider pr = Cfg.getSC().getProvider(prn);
		if(pr!=null){
			return pr;
		}
		//ap主动报,多个AP接入时无法解决来自哪个AP
        pr = new Provider(new Keeper(),prn);
        Cfg.getSC().addProvider(pr);		
		return pr;
	}
    public void sessionOpened(IoSession session) throws Exception {
    }

    /**
     * This method will be called whenever an exception occurs.  For this handler,
     * the logger will generate a warning message.
     * 
     * @see org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(org.apache.mina.core.session.IoSession, java.lang.Throwable)
     */
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    }

    /**
     * Handle incoming messages.
     * 
     * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(org.apache.mina.core.session.IoSession, java.lang.Object)
     */
    public void messageReceived(IoSession session, Object message) throws Exception {
    	 ImageResponse response = (ImageResponse) message;
         if(response.getFh().getFrame_type()==FrameHeader.FRAME_TYPE_HEART){
         	//收到心跳帧
             IoBuffer buffer = IoBuffer.allocate(4, false);
             buffer.putInt(ack);
             buffer.flip();
         	session.write(buffer);
         }else{
         	//收到图像帧
 	        onImage(response.getFh(), response.getImage1());
         }
    }

    
    public Plate getPlt(){
    	if(plt==null){
    		plt = new Plate("TH_PlateResult");
    		plt.InitPlate();
    	}
    	return plt;
    }
    private String parseResult(String fn){
    	//TODO jni调用号牌识别
    	if(bjni){
    		return getPlt().GetPlateResult(fn);
    	}else{
    		return randResult();
    	}
    }
    private String randResult(){
    	pos_rs++;
    	if(pos_rs==RS.length){
    		pos_rs=0;
    	}
    	return RS[pos_rs];
    }
    private void onImage(FrameHeader fh,BufferedImage image1){
		Date dt = new Date();
		long dev_no = fh.getDevice_no();
		String fpath = Cfg.getInitParameter("work_path")+dev_no;
		File fp = new File(fpath);
		if(fp.exists()||!fp.isDirectory()){
			fp.mkdir();
		}
		fpath+=File.separator;
		
		long tm = dt.getTime();
		String fn1 =fpath+"f1-"+tm+"."+IMG_FMT;
/*		try {
			ImageIO.write(image1, IMG_FMT, new File(fn1));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
*/		
		ImgServlet.setImg((int)dev_no,image1);
		State s = new State();
		s.setAction(State.ACTION_PUT);
		s.setCn(CN_CAMERA);
		HashMap its = new HashMap();
		its.put("fn", fn1);
		its.put("tm", tm);
		its.put("result", parseResult(fn1));
		s.setKey(dev_no);
		s.setItems(its);
		getPR(fh.getDevice_no()).send(s);
		//TODO send State for websocket
    }

}
